#!/bin/bash
#
# Copyright (C) 2006-2015  Seznam.cz, a.s.
#

set -e

export PKG_CONFIG_PATH="/opt/szn/lib/amd64:/usr/lib/amd64/pkgconfig"
export LDFLAGS="-m64 -L/opt/szn/lib/amd64"
export CXXFLAGS="-m64 -DSOLARIS"
export CFLAGS="-m64 -DSOLARIS"
export CPPFLAGS="-m64 -DSOLARIS"

# Maintainer of this module
MAINTAINER=""

# Where are the sources
SOURCE_DIR="../"

########################################################################
# Command line options.                                                #
########################################################################
while [ "$#" != "0" ]; do
    case "$1" in
        --help)
            echo "Usage: ${SELF} [--debug] [--help]"
            echo "    --skip-build         skip building binaries, install and pack"
            echo "    --skip-install       skip building and installing binaries, just pack"
            echo "    --debug              log every command to stderr (set -x)"
            echo "    --help               show this help"
            echo ""
            echo "    To change package's version please edit file configure.in in upper"
            echo "    directory. Package info file is generated by expanding @tags@ in the"
            echo "    <PACKAGE_NAME>.pkginfo file."
            echo ""
            echo "    You can also create <PACKAGE_NAME>.postinstall, <PACKAGE_NAME>.preinstall,"
            echo "    <PACKAGE_NAME>.conffiles, <PACKAGE_NAME>.preremove "
            echo "    <PACKAGE_NAME>.postremove and <PACKAGE_NAME>.checkinstall files that would"
            echo "    be used as postinstall, preinstall, conffiles, preremove and postremove"
            echo "    and checkinstall files in the package."
            echo ""
            echo "    You should create <PACKAGE_NAME>.configfl file to shadow the default"
            echo "    configure options."
            echo ""
            echo "    Tou can create file <PACKAGE_NAME>.dirs to specify the directories"
            echo "    you want to create."
            echo ""
            echo "    You can also specify the files to be copied before building package"
            echo "    in file <PACKAGE_NAME>.copy"
            exit 0
        ;;

        --debug)
            DEBUG="debug"
        ;;

        --skip-build)
            SKIP_BUILD="yes"
        ;;

        --skip-install)
            SKIP_BUILD="yes"
            SKIP_INSTALL="yes"
        ;;

        --with-*)
            PACKAGE="${PACKAGE} `echo $1|sed 's/--with-//g'`"
        ;;


        # The flag for recursvie ${SELF} calling with fakeroot.
        --no-fakeroot-test)
            NO_FAKEROOT_TEST="yes"
        ;;

        *)
            echo "Unknown option '$1', try ${SELF} --help." >> /dev/stderr
            exit 1
        ;;
    esac
    shift
done

if test "$DEBUG" = "debug"; then
    set -x
fi

function test_fakeroot {
    save_IFS=$IFS
    IFS=":"
    for dir in $PATH ; do
        IFS=$save_IFS
        test -z "$as_dir" && as_dir=.

        if { test -f "$dir/fakeroot" && test -x "$dir/fakeroot"; }; then
            fakeroot_found="yes"
            fakeroot_cmd="fakeroot"
            break 1
        fi
    done

    IFS=$save_IFS

    if test -z "$fakeroot_found"; then
        fakeroot_found="no"
        fakeroot_cmd=""
    fi
}


function replace_vars {
    sed -e "s/@VERSION@/${VERSION}/" \
        -e "s/@MAINTAINER@/${MAINTAINER}/" \
        -e "s/@PACKAGE@/${PACKAGE_NAME}/" \
        $1 > $2
}

function make_dirs {
    cd build
    if test -f ../$1.dirs ; then
        DIRS=`cat ../$1.dirs`
        mkdir -p ${DIRS}
    fi
    cd ..
}

function copy_files {
    if test -f $1.copy ; then
        while read line; do
            cp ${line}
        done < $1.copy
    fi
}

function create_package {
    # Determine version
    VERSION=$(< ${SOURCE_DIR}/version)
    VERSION="$VERSION,REV=$(date '+%Y.%m.%d')"

    PACKAGE_NAME=$1

    rm -f cfgfiles
    rm -Rf build/install
    mkdir -p build/install

    replace_vars ${PACKAGE_NAME}.pkginfo build/install/pkginfo
    echo "i pkginfo" >>cfgfiles ;

    for cfgf in checkinstall conffiles depend preinstall postinstall preremove postremove ; do
        if test -f ${PACKAGE_NAME}.${cfgf} ; then
            cp ${PACKAGE_NAME}.${cfgf} build/install/${cfgf}
            echo "i ${cfgf}" >>cfgfiles ;
        fi ;
    done

    make_dirs ${PACKAGE_NAME}
    copy_files ${PACKAGE_NAME}

    ${fakeroot_cmd} chown -R root:root build

    cd build
    FILES=`cat ../${PACKAGE_NAME}.files`

    if test -z ${FILES}; then
        cd ..
        return
    fi

    proto_list ${FILES} | ${fakeroot_cmd} pkgproto >> install/prototype
    cd ..

    cat cfgfiles >>build/install/prototype

    mkdir -p pkg
    ${fakeroot_cmd} pkgmk -o -f build/install/prototype -b `pwd`/build -d `pwd`/pkg
    ${fakeroot_cmd} pkgtrans -s `pwd`/pkg `pwd`/${PACKAGE_NAME}-${VERSION}.pkg ${PACKAGE_NAME}
    gzip -f ${PACKAGE_NAME}-${VERSION}.pkg
}


function install_package {
    cd ..

    rm -Rf `pwd`/solaris/build
    make DESTDIR=`pwd`/solaris/build install

    cd solaris
}


function build_package {
    cd ..

    if test -z "${PREV_BUILD}" || test "${PREV_BUILD}" != "$*"; then
        {
            autoreconf -if

            if test $# -ne 0; then
                PREV_BUILD=$*
            else
                PREV_BUILD=""
            fi

            ./configure ${PREV_BUILD}

            make clean
        }
    fi

    make -j8

    cd solaris
}


function build_and_install_package {
    if test -f $1.configfl; then
        CFGARGS=`cat $1.configfl`
    fi

    if test -z "${SKIP_BUILD}"; then
        build_package $CFGARGS
        install_package
    elif test -z "${SKIP_INSTALL}"; then
        install_package
    fi
}

function prepare_dev {
    PKG_NAME="$1"
    PKG_DEVNAME="$1-dev"

    if ! test -f "${PKG_DEVNAME}.pkginfo"; then
        cp ${PKG_NAME}.pkginfo ${PKG_DEVNAME}.pkginfo
        remove_pkginfo="yes"
    else
        remove_pkginfo="no"
    fi

    if ! test -f "${PKG_DEVNAME}.files"; then
        find ./build/usr -type f |sed 's/.\/build\///g'>tmp.files

        for file in `cat ${PKG_NAME}.files`; do
            test -f "build/$file" && echo $file >>tmp.files
        done

        cat tmp.files | sort | \
            awk 'BEGIN {prev="";print_prev="no";}
                       {if (prev != $0) {
                            if (print_prev == "yes") {
                                print prev;
                            }
                            prev=$0; print_prev="yes"
                        } else {
                            print_prev="no";
                        }
                       }
                 END {if (print_prev == "yes") print prev;}' >${PKG_DEVNAME}.files

        rm tmp.files

        remove_files="yes"
    else
        remove_files="no"
    fi

}

function clean_dev {
    PKG_DEVNAME="$1-dev"

    if test "x$remove_pkginfo" = xyes; then
        rm ${PKG_DEVNAME}.pkginfo
    fi

    if test "x$remove_files" = xyes; then
        rm ${PKG_DEVNAME}.files
    fi
}

# List files with all parrent directories
function proto_list {
    while [ $# -gt 0 ] ; do
        path="$1" ; shift
        while [ "$path" != "." ] ; do
            echo $path
            path=$(dirname "$path")
        done
    done | sort -u
}

if test -z ${MAINTAINER}; then
    echo "Please fill in the MAINTAINER at the beginnging of this script before" >&2
    echo "building the package." >&2
    exit 1
fi

# Test the presence of fakeroot.
if test -z ${NO_FAKEROOT_TEST}; then
    test_fakeroot
fi


# Proccess all the packages.
if test -z "${PACKAGE}"; then
# Proccess all the packages.
    (
        for pkg in *.pkginfo ; do
            # Get the package name.
            pkgname=`echo ${pkg}|sed 's/.pkginfo//g'`

            build_and_install_package ${pkgname}
            create_package ${pkgname}
#             prepare_dev ${pkgname}
#             create_package "${pkgname}-dev"
#             clean_dev ${pkgname}
        done
    )
else
    (
        for pkg in ${PACKAGE} ; do
            # Get the package name.
            pkgname=`echo ${pkg}|sed 's/.pkginfo//g'`

            build_and_install_package ${pkgname}
            create_package ${pkgname}
#             prepare_dev ${pkgname}
#             create_package "${pkgname}-dev"
#             clean_dev ${pkgname}
        done
    )
fi

#rm -Rf build
#rm -Rf pkg
rm -f cfgfile

